﻿using Window = System.Windows.Window;

namespace WordCloudClient
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        public App()
        {
            //首先注册开始和退出事件
            Startup += new StartupEventHandler(App_Startup);
            Exit += new ExitEventHandler(App_Exit);
        }
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            //// 注册导航
            containerRegistry.RegisterForNavigation<ViewSystemSetting>();
            containerRegistry.RegisterForNavigation<ViewGenerateWordCloud>();
            containerRegistry.RegisterForNavigation<ViewRule>();
            containerRegistry.RegisterForNavigation<ViewFilterWords>();
            //// 注册对话窗口
            containerRegistry.RegisterDialog<WinAboutSystem, WinAboutSystemViewModel>();
            containerRegistry.RegisterDialog<WinEditDictionary, WinEditDictionaryViewModel>();
            containerRegistry.RegisterDialog<WinEditFilter, WinEditFilterViewModel>();

        }
        /// <summary>
        /// 自定义视图对应视图模型
        /// </summary>
        protected override void ConfigureViewModelLocator()
        {
            base.ConfigureViewModelLocator();
            ViewModelLocationProvider.Register<MainWindow, MainWindowViewModel>();
        }
        public Mutex? Mutex;
        void App_Startup(object sender, StartupEventArgs e)
        {
            string strProcessName = Process.GetCurrentProcess().ProcessName;
            Mutex = new(true, strProcessName, out bool ret);
            if (!ret)
            {
                MessageTips.InfoMessage("程序已启动！");
                Environment.Exit(0);
            }
            //UI线程未捕获异常处理事件
            DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);

            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException!;

            //非UI线程未捕获异常处理事件
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }
        void App_Exit(object sender, ExitEventArgs e)
        {
            //程序退出时需要处理的业务
        }
        /// <summary>
        /// UI线程未捕获异常处理事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                e.Handled = true; //把 Handled 属性设为true，表示此异常已处理，程序可以继续运行，不会强制退出      
                MessageTips.ErrorMessage("UI线程捕获未处理异常:" + e.Exception.Message);
            }
            catch (Exception ex)
            {
                //此时程序出现严重异常，将强制结束退出
                MessageTips.ErrorMessage("程序发生致命错误，将终止！\n" + ex.Message);
            }

        }
        /// <summary>
        /// 非UI线程未捕获异常处理事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            StringBuilder sbEx = new();
            if (e.IsTerminating)
            {
                sbEx.Append("程序发生致命错误，将终止！\n");
            }
            sbEx.Append("非UI线程捕获未处理异常：");
            if (e!.ExceptionObject is Exception)
            {
                sbEx.Append(((Exception)e.ExceptionObject).Message);
            }
            else
            {
                sbEx.Append(e.ExceptionObject);
            }
            MessageTips.ErrorMessage(sbEx.ToString());
        }

        /// <summary>
        /// Task线程内未捕获异常处理事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            //task线程内未处理捕获
            MessageTips.ErrorMessage("捕获线程内未处理异常：" + e.Exception.Message);
            e.SetObserved();//设置该异常已察觉（这样处理后就不会引起程序崩溃）
        }
    }
}
